import { Button, Card, Popconfirm, message } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { useEffect, useState } from 'react';

import regionService from '@/api/services/security/regionService';
import { IconButton, Iconify } from '@/components/icon';
import { datetime } from '@/utils/format-date';
import { hasPermission } from '@/utils/permission';
import { listToTree } from '@/utils/tree';

import RegionPageModal from './region-modal';
import { Region } from './type';

import { ModalProps } from '#/entity';

const DEFAULT_REGION_VALUE: Region = {
  name: '',
  createAt: [],
  id: 0,
  namePath: '',
  depth: 0,
  code: '',
  parent: undefined,
};
export default function RegionPage() {
  const [tableData, setTableData] = useState<Region[]>();
  const [reload, setReload] = useState<boolean>();
  const [modalProps, setModalProps] = useState<ModalProps<Region>>({
    formValue: DEFAULT_REGION_VALUE,
    title: '',
    show: false,
    onOk: () => {
      setModalProps((prev) => ({ ...prev, show: false }));
      setReload(true);
    },
    onCancel: () => {
      setModalProps((prev) => ({ ...prev, show: false }));
      setReload(true);
    },
  });
  useEffect(() => {
    regionService.tree().then((res) => {
      setTableData(listToTree(res));
    });
  }, [reload]);
  // ... 其他代码保持不变 ...
  const columns: ColumnsType<Region> = [
    {
      title: '名称',
      dataIndex: 'name',
      width: 100,
    },
    {
      title: '路径名称',
      dataIndex: 'namePath',
      width: 150,
    },
    {
      title: '区域编号',
      dataIndex: 'code',
      width: 50,
    },
    {
      align: 'center',
      title: '深度',
      dataIndex: 'depth',
      width: 100,
    },
    {
      align: 'center',
      title: '创建时间',
      dataIndex: 'createdAt',
      width: 100,
      render: (_, record: Region) => {
        return datetime(record.createAt);
      },
    },

    {
      fixed: 'right',
      title: <div style={{ marginRight: '38px', float: 'right' }}>操作</div>,
      key: 'operation',
      align: 'center',
      width: 20,
      render: (_, record) => (
        <div className="flex w-full justify-end text-gray">
          {hasPermission('WINE:REGION:CREATE') && (
            <IconButton onClick={() => onItemCreate(record)}>
              <Iconify icon="gridicons:add-outline" size={18} />
            </IconButton>
          )}
          {hasPermission('WINE:REGION:UPDATE') && (
            <IconButton onClick={() => onEdit(record)}>
              {/* 编辑 */}
              <Iconify icon="solar:pen-bold-duotone" size={18} />
            </IconButton>
          )}
          {hasPermission('WINE:REGION:DELETE') && (
            <Popconfirm
              title={() => {
                if (record.children) {
                  return `确定要删除区域  ${record.name}  ？删除后该区域下子级将全部删除`;
                }
                return `确定要删除区域  ${record.name}  ？  `;
              }}
              okText="确定"
              cancelText="取消"
              placement="left"
              onConfirm={() => {
                onDelete(record);
              }}
            >
              <IconButton>
                <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
              </IconButton>
            </Popconfirm>
          )}
        </div>
      ),
    },
  ];

  const onItemCreate = (formValue: Region) => {
    setModalProps((prev) => ({
      ...prev,
      show: true,
      title: '创建区域',
      formValue,
    }));
  };
  const onVoidCreate = () => {
    setModalProps((prev) => ({
      ...prev,
      show: true,
      title: '创建区域',
      formValue: { ...DEFAULT_REGION_VALUE },
    }));
  };
  const onEdit = (formValue: Region) => {
    const newCode = formValue.code.replace(formValue.parent!.code, '');

    setModalProps((prev) => ({
      ...prev,
      show: true,
      title: '修改区域',
      formValue: { ...formValue, code: newCode },
    }));
  };
  const onDelete = async (record: Region) => {
    regionService
      .deleteRegion(record.id!)
      .then(() => {
        message.success('删除成功');
        setReload(true);
      })
      .catch(() => {
        message.error('删除失败');
      });
  };

  return (
    <Card
      title="区域管理"
      extra={
        hasPermission('WINE:REGION:CREATE') && (
          <Button type="primary" onClick={onVoidCreate}>
            创建
          </Button>
        )
      }
    >
      <Table
        rowKey="id"
        size="small"
        scroll={{ x: 'max-content' }}
        pagination={false}
        columns={columns}
        dataSource={tableData}
      />
      <RegionPageModal {...modalProps} />
    </Card>
  );
}
